package com.hbu.search.hbumallsearch.service.impl;

import com.alibaba.fastjson2.JSON;
import com.hbu.common.TO.es.SkuEsModel;
import com.hbu.search.hbumallsearch.service.ElasticSearchService;
import com.hbu.search.hbumallsearch.utils.EsConstant;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.bulk.BulkItemResponse;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.List;

/**
 * @author 90458
 */
@Slf4j
@Service
@AllArgsConstructor
public class ElasticSearchServiceImpl implements ElasticSearchService {

    private RestHighLevelClient restHighLevelClient;

    @Override
    public void productShelves(List<SkuEsModel> skuEsModelList) throws IOException {
        BulkRequest bulkRequest = new BulkRequest();
        skuEsModelList.forEach(skuEsModel -> {
            IndexRequest indexRequest = new IndexRequest(EsConstant.PRODUCT_INDEX);
            indexRequest.id(String.valueOf(skuEsModel.getSkuId()));
            indexRequest.source(JSON.toJSONString(skuEsModel), XContentType.JSON);
            bulkRequest.add(indexRequest);
        });
        BulkResponse response = restHighLevelClient.bulk(bulkRequest, RequestOptions.DEFAULT);
        log.debug("完成插入:{}", response.status());
        if (response.hasFailures()) {
            log.error("商品上架错误:{}", response.buildFailureMessage());
            for (BulkItemResponse item : response.getItems()) {
                log.error("错误信息为:" + item.getFailureMessage());
            }
        }
    }

}
